import Vue from 'vue';
// 验证token是否失效
var expired = false;
const host = 'https://www.uinav.com';

function request(url, param, way, res) {
	let token = uni.getStorageSync('token');
	uni.request({
		url: host + url,
		data: param,
		header: {
			'RM-TOKEN':token ?? '',
			'Content-Type': "application/json" //传参类型
		},
		method: way,
		success: (data) => {
			res(data.data)
		},
		fail: () => {
			res({
				data: { data: {}, msg: "请求失败" }
			})
		}
	});
}

export default {
	init() {
		console.log("*** http installed ***");
		Vue.prototype.$http = {
			request: this.request,
			getHost: this.getHost,
		}
	},
	request: async function(url, param, way = 'POST', showLoading = true) {
		if (showLoading)
			uni.showLoading({
				title: "正在加载",
				mask: true
			})
		return await new Promise(resolve => {
			request(url, param, way, (res) => {
				if (showLoading) uni.hideLoading();
				if (res?.msg == '身份已过期' && !expired) {
					uni.removeStorage({key: 'token'})
					uni.reLaunch({ url: '/pages/index/login/mobile-login'});
					expired = true
				}
				expired = false
				resolve(res)
			});
		})
	},
	getHost() {
		return host;
	},
}
